﻿using LPP.Entity.AppUser;
using LPP.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace LPP.Service.UserRepository
{
    public interface IUserService
    {
    
        Task<Users> GetUserByPhoneNumberAsync(string phoneNumber);
        Task<int> CreateUserAsync(Users user); // 修改为返回 int
        Task<Users> GetUserByIdAsync(int id);
        Task<bool> DeleteUserAsync(int id); // 软删除方法
        Task<bool> UpdateUserAsync(Users user);  
    }


    public class UserService : IUserService
    {
        private readonly IUserRepository _userRepository;
        private readonly SqlDbContext _dbContext;

        public UserService(IUserRepository userRepository, SqlDbContext dbContext)
        {
            _userRepository = userRepository;
            _dbContext = dbContext;
        }

        public async Task<Users> GetUserByPhoneNumberAsync(string phoneNumber)
        {
            return await _dbContext.Users.FirstOrDefaultAsync(u => u.PhoneNumber == phoneNumber && !u.IsDelete); // 排除被软删除的用户
        }

        public async Task<int> CreateUserAsync(Users user)
        {
            // 检查是否存在相同手机号的软删除用户
            var existingUser = await _dbContext.Users.FirstOrDefaultAsync(u => u.PhoneNumber == user.PhoneNumber && u.IsDelete);
            if (existingUser != null)
            {
                // 恢复已软删除的用户
                existingUser.IsDelete = false;
                _dbContext.Users.Update(existingUser);
                await _dbContext.SaveChangesAsync();
                return existingUser.UserID; // 返回恢复的用户ID
            }

            // 如果没有软删除的用户，创建新用户
            _dbContext.Users.Add(user);
            await _dbContext.SaveChangesAsync();
            return user.UserID;
        }
        public async Task<Users> GetUserByIdAsync(int id)
        {
            return await _dbContext.Users.FirstOrDefaultAsync(u => u.UserID == id && !u.IsDelete); // 排除软删除的用户
        }

        // 实现软删除
        public async Task<bool> DeleteUserAsync(int id)
        {
            var user = await _dbContext.Users.FindAsync(id);
            if (user == null || user.IsDelete) // 用户不存在或已经删除
            {
                return false;
            }

            user.IsDelete = true; // 设置软删除
            _dbContext.Users.Update(user); // 更新用户状态
            return await _dbContext.SaveChangesAsync() > 0; // 返回是否成功
        }
        public async Task<bool> UpdateUserAsync(Users user)
        {
            _dbContext.Users.Update(user);
            return await _dbContext.SaveChangesAsync() > 0;
        }
    }
}
